package us.bighelp2.marc.dataservices;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import us.bighelp2.marc.common.AppDBConnection;
import us.bighelp2.marc.common.Queries;
import us.bighelp2.marc.resources.Password;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(LoginServlet.class);
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		response.setContentType("application/json");
		PrintWriter pw = response.getWriter();
		AppDBConnection bhdbcon = new AppDBConnection("marc");
		
		try
		{
			//Get entered value
			String user = request.getParameter("user");
			String pwd = request.getParameter("pwd");
			String correctPW = null;

			if(logger.isDebugEnabled()){logger.debug("Begin authenticating user: " + user);}
			
			//Find user in DB and pull back the hashed password
			Connection conn = bhdbcon.getConnection();
			PreparedStatement ps = conn.prepareStatement(Queries.SQL_AUTHENTICATE_USER);
			try
			{
				ps.setString(1, user);
				ResultSet rs = ps.executeQuery();
				if(rs.next())
				{
					correctPW = rs.getString("Password");
					
					if(Password.checkPassword(pwd,correctPW))
					{
						if(logger.isDebugEnabled()){logger.debug(user + " authenticated! Redirecting with cookie.");}
						
						Cookie loginCookie = new Cookie("user",user);
						//setting cookie to expiry in 30 mins
						loginCookie.setMaxAge(30*60);
						response.addCookie(loginCookie);
						response.sendRedirect("index.jsp");
					}
					else
					{
						if(logger.isDebugEnabled()){logger.debug("INVALID LOGON: " + user);}
						
						RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.jsp");
						pw.println("<font color=red>Either user name or password is wrong.</font>");
						rd.include(request, response);
					}
				}
				else
				{
					if(logger.isDebugEnabled()){logger.debug("INVALID LOGON: " + user);}
					
					RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.jsp");
					pw.println("<font color=red>Either user name or password is wrong.</font>");
					rd.include(request, response);
				}
			}
			finally
			{
				ps.close();
				conn.close();
			}
		}
		catch(SQLException se)
		{
			se.printStackTrace();
		}
		finally
		{
			
		}
	}
}